<template>
  <div class="app-container">
    <div>
      <el-form :model="queryParams" :rules="rules" ref="queryForm" size="small" :inline="true" label-width="100px">
        <el-form-item style="margin-left: -25px" label="乘客姓名" prop="passengerName">
          <el-select
            v-model="queryParams.passengerName"
            filterable
            @change="handleChange"
          >
            <el-option
              v-for="item in ckXmOptions"
              :key="item.ckName"
              :label="item.ckName"
              :value="item.ckName"
              :disabled="flag || single"
            />
          </el-select>
        </el-form-item>
        <el-form-item @change="handleChangeCard" style="margin-left: -10px" label="乘客证件号" prop="passengerIdCard">
          <el-select
            v-model="queryParams.passengerIdCard"
            filterable
          >
            <el-option
              v-for="item in ckIdCardOptions"
              :key="item.label"
              :label="item.label"
              :value="item.value"
              :disabled="flag || single"
            />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: -25px" label="登机类型" prop="djLx">
          <el-select @change="handleChangeDjlx" v-model="queryParams.djLx" clearable style="width: 120px">
            <el-option
              v-for="dict in dict.type.dj_lx"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="flag || single"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button :disabled="flag || single" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <iframe id="myIframe"
              src="http://localhost:2349"
              width="100%"
              height="800px"
              style="margin-top: 0px"
      ></iframe>
    </div>
  </div>
</template>

<script>

import { selectCkXlDynamicInfo, getCkXmInfo, getCkIdCardByCkXm } from '@/api/ckxl/ck'
export default {
  name: 'Dynamics',
  dicts: ['dj_lx'],
  data() {
    return {
      // 查询参数
      queryParams: {
        passengerName: '',
        passengerIdCard: '',
        djLx: '0'
      },
      rules: {
        passengerName: [
          { required: true, message: '乘客姓名不能为空', trigger: 'blur' }
        ],
        passengerIdCard: [
          { required: true, message: '乘客证件号不能为空', trigger: 'blur' }
        ]
      },
      ckXmOptions: [{
        label:"",
        value:""
      }],
      ckIdCardOptions: [],
      //乘客行李动态跟踪
      ckxlDynamicInfo:'',
      flag: false,
      single: false,
      ckMap: null,
    }
  },
  watch: {
    '$store.state.user.peopleNum': {
      handler:function(newVal,oldVal){
        if(newVal != oldVal){
          this.queryParams.passengerName = '';
          this.queryParams.passengerIdCard = '';
          this.getCkBaseInfo();
        }
      }
    }
  },
  created() {
  },
  computed: {},
  mounted() {
    this.queryParams.passengerName = '';
    this.queryParams.passengerIdCard = '';
    this.getCkBaseInfo();
    const _that = this;
    window.addEventListener('message', function (event) {
      console.log(event.data)
      if (event.origin === 'http://localhost:2349') { // 验证消息来源是否可信
        if(event.data  == 'success'){
          _that.successCallBack();
          _that.ckMap = new Map();
          _that.ckMap.set('cardNo', _that.queryParams.passengerIdCard);
        }
      }
    });
  },
  methods: {

    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs['queryForm'].validate(valid => {
        if (valid) {
          const flag = this.checkZjMap();
          if(!flag && this.queryParams.djLx == '1'){
            this.$message.error('请先查询直达行李运动轨迹！');
          }
          if(flag){
            this.getCkDynamicInfo()
          }
        }
      })
    },

    //校验是否先执行值机轨迹查询
    checkZjMap(){
      let flag = true;
      if(this.ckMap != null){
        this.ckMap.forEach((value, key) => {
          if (this.queryParams.djLx == '1' && value !== this.queryParams.passengerIdCard) {
            flag = false;
          }
          if(this.queryParams.djLx == '0' && value === this.queryParams.passengerIdCard){
            this.$message({
              message: '当前乘客直达行李运动轨迹已跟踪完成！',
              type: 'warning'
            });
            flag = false;
          }
        });
      }
      if(this.ckMap == null && this.queryParams.djLx == '1'){
        flag = false;
      }
      return flag;
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryIsTransfer = '';
      //页面刷新重置
      this.flushIndex();
      this.ckXmOptions = [];
      this.ckIdCardOptions = [];
      this.getCkBaseInfo();
      this.flag = false;
      this.single = false;
    },

    /** 查询乘客 动态节点信息 */
    getCkDynamicInfo: function() {
      this.fillCkIdCard();
      selectCkXlDynamicInfo(this.queryParams).then(response => {
        this.ckxlDynamicInfo = response.data
        //处理信息
        const jsonStr = JSON.stringify(this.ckxlDynamicInfo);
        this.sendMessage(jsonStr)
        if(this.queryParams.djLx == '0'){
          this.flag = true;
        }
        if(this.queryParams.djLx == '1'){
          this.single = true;
        }
      })
    },

    // 获取真正的乘客证件号
    fillCkIdCard(){
      this.ckIdCardOptions.forEach(item => {
        if(item.label == this.queryParams.passengerIdCard){
          this.queryParams.passengerIdCard = item.value;
        }
      })
    },

    /** 发送信息 */
    sendMessage(jsonStr) {
      const iframe = document.getElementById('myIframe');
      iframe.contentWindow.postMessage(jsonStr, 'http://localhost:2349');
    },

    // 防抖处理（500ms内仅触发一次）
    getCkBaseInfo() {
      getCkXmInfo().then(response => {
        if (response.data != null) {
          this.ckXmOptions = response.data
        }
      }).catch(() => {
        this.ckXmOptions = [];
      });
    },

    //选中乘客姓名
    handleChange(value){
      this.flushIndex();
      this.getCkIdCard(value);
    },

    //根据乘客姓名查询乘客身份证id
    getCkIdCard(ckName){
      getCkIdCardByCkXm(ckName).then(response => {
        this.ckIdCardOptions = [];
        if (response.data != null) {
          response.data.forEach(item => {
              this.ckIdCardOptions.push({
                'label': this.formatIdCard(item.idCard),
                'value': item.idCard
              })
            }
          )
          this.queryParams.passengerIdCard = this.ckIdCardOptions[0].label;
        }
      }).catch(() => {
        this.ckIdCardOptions = [];
      });
    },

    // 格式化显示身份证号（如：410*****123456）
    formatIdCard(idCard) {
      if(idCard != null){
        return idCard.replace(/(\d{4})\d+(\d{6})/, '$1*****$2');
      }
    },

    // 登机类型变化
    successCallBack() {
      this.flag = false;
    },

    handleChangeDjlx(value){
      if(value == '0'){
        this.flushIndex();
      }
    },

    handleChangeCard(){
      this.flushIndex();
    },

    flushIndex(){
      this.ckMap = null;
      //页面刷新重置
      const iframe = document.getElementById('myIframe');
      let tempSrc = iframe.src;
      iframe.src = "about:blank";
      iframe.src = tempSrc;
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
